import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/app/controllers/downloader_controller.dart';
import 'package:flutter_app/app/models/download.dart';
import 'package:flutter_app/app/models/movie.dart';
import 'package:flutter_app/resources/pages/play_page.dart';
import 'package:nylo_framework/nylo_framework.dart';

class DownloadPage extends NyStatefulWidget<DownloaderController> {
  static RouteView path = ("/download", (_) => DownloadPage());

  DownloadPage({super.key}) : super(child: () => _DownloadPageState());
}

class _DownloadPageState extends NyPage<DownloadPage> {
  /// [DownloaderController] controller
  DownloaderController get controller => widget.controller;

  List<Download> downloads = [];
  Timer? _refreshTimer;

  LoadingStyle get loadingStyle => LoadingStyle.normal(
        child: CupertinoActivityIndicator(),
      );

  Future<void> _fetchTasks() async {
    var task = await controller.getTasks();
    if (mounted) {
      setState(() {
        downloads = task;
      });
    }
  }

  @override
  get init => () async {
        await _fetchTasks();
        _refreshTimer = Timer.periodic(Duration(seconds: 1), (timer) {
          _fetchTasks();
        });
      };

  @override
  void dispose() {
    _refreshTimer?.cancel();
    super.dispose();
  }

  @override
  Widget view(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Center(child: Text("下载记录"))),
      body: Padding(
        padding: const EdgeInsets.all(4.0),
        child: SafeArea(
          child: downloads.isEmpty
              ? Center(child: Text("暂无下载记录"))
              : ListView.builder(
                  itemCount: downloads.length,
                  itemBuilder: (_, index) {
                    final task = downloads[index];
                    return Container(
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(
                          4,
                        ),
                      ),
                      margin: EdgeInsets.only(bottom: 4),
                      child: ListTile(
                        titleAlignment: ListTileTitleAlignment.center,
                        style: ListTileStyle.drawer,
                        title: Text(
                          task.name!,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            LinearProgressIndicator(
                              borderRadius: BorderRadius.circular(10),
                              value: task.progress! / 100,
                              backgroundColor: Colors.grey[200],
                              valueColor:
                                  AlwaysStoppedAnimation<Color>(Colors.blue),
                            ),
                            SizedBox(height: 4),
                            Text(
                              '${task.progress}% - ${task.status}',
                              style: Theme.of(context).textTheme.bodySmall,
                            ),
                          ],
                        ),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            if (task.status == DownloadStatusDownloading)
                              IconButton(
                                icon: Icon(Icons.pause),
                                onPressed: () async {
                                  await controller.pauseTask(task.id!);
                                  await _fetchTasks();
                                },
                              ),
                            if (task.status == DownloadStatusPaused)
                              IconButton(
                                icon: Icon(Icons.downloading),
                                onPressed: () async {
                                  await controller.resumeDownload(task.id!);
                                  await _fetchTasks();
                                },
                              ),
                            if (task.status == DownloadStatusDownloading ||
                                task.status == DownloadStatusPaused ||
                                task.status == DownloadStatusCompleted)
                              IconButton(
                                icon: Icon(
                                  Icons.delete,
                                  color: Colors.red[600],
                                ),
                                onPressed: () async {
                                  await controller.deleteTask(task);
                                  await _fetchTasks();
                                },
                              ),
                            if (task.status == DownloadStatusFailed)
                              IconButton(
                                icon: Icon(Icons.refresh),
                                onPressed: () {},
                              ),
                            if (task.status == DownloadStatusPending)
                              IconButton(
                                icon: Icon(Icons.download),
                                onPressed: () {},
                              ),
                          ],
                        ),
                        onTap: () {
                          if (task.status != DownloadStatusCompleted) return;
                          MoviesList movie =
                              MoviesList.fromJson(jsonDecode(task.movie!));
                          movie.localfile = task.savePath ?? '';
                          routeTo(PlayPage.path, data: movie);
                          NyLogger.dump("打开文件${task.savePath}", "open file");
                        },
                      ),
                    );
                  },
                ),
        ),
      ),
    );
  }
}
